package com.pospi.pai.yunpos.bh;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.caigou.StatusBeen;
import com.pospi.pai.yunpos.diaob.BillBeen;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;
import com.pospi.util.GetData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lib.kingja.switchbutton.SwitchMultiButton;

/*
*调拨收货
 */

public class SupAotoListActivity extends Base2Activity {
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.list_bill)
    ListView list_bill;
    @Bind(R.id.tv_psmd)
    TextView tv_psmd;

    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    private List<StatusBeen> statusBeens = new ArrayList<>();
    private MyAdapter adapter;
    private EditText sl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_bh_list);
        ButterKnife.bind(this);
        setTitle("门店补货建议单");
        init();
        downStore();
    }


    private void init() {
        adapter = new MyAdapter();
        list_bill.setAdapter(adapter);
        list_bill.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BhGoodsBeen goodsBeen = beens.get(position);
                new CircleDialog.Builder(SupAotoListActivity.this)
                        .setBodyView(R.layout.dialog_layout_bh, new OnCreateBodyViewListener() {
                            @Override
                            public void onCreateBodyView(View view) {
                                sl = view.findViewById(R.id.et_goods_num);
                                TextView kc = view.findViewById(R.id.tv_kcsl);
                                kc.setText(goodsBeen.getKcsl());
                            }
                        })
                        .setWidth(0.5f)
                        .setPositive("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (NumberCheck(sl.getText().toString().trim())) {
                                    goodsBeen.setSuj(String.valueOf(Double.parseDouble(sl.getText().toString().trim())));
                                }
                                adapter.notifyDataSetChanged();
                            }
                        })
                        .setCancelable(false)
                        .setTitle(goodsBeen.getName())
                        .setNegative("取消", null)
                        .show();

            }
        });
    }

    private List<BhGoodsBeen> beens = new ArrayList<>();

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return beens.size();
        }

        @Override
        public Object getItem(int i) {
            return beens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder ;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(SupAotoListActivity.this).inflate(R.layout.bh_bill_item, null);
                holder.code = view.findViewById(R.id.code);
                holder.name = view.findViewById(R.id.name);
                holder.tv_sl = view.findViewById(R.id.tv_sl);
                holder.tv_jysl = view.findViewById(R.id.tv_jysl);
                holder.tv_lsl = view.findViewById(R.id.tv_lsl);
                holder.tv_hsl = view.findViewById(R.id.tv_hsl);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }

            BhGoodsBeen been = beens.get(i);
            holder.code.setText(been.getBarcode());
            holder.name.setText(been.getName());
            holder.tv_sl.setText(been.getKcsl());
            holder.tv_jysl.setText(been.getSuj());
            holder.tv_lsl.setText(been.getMin());
            holder.tv_hsl.setText(been.getMax());
            return view;
        }
        class Holder{
            TextView code;
            TextView name;
            TextView tv_sl;
            TextView tv_jysl;
            TextView tv_lsl;
            TextView tv_hsl;
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    closeLodindDialog();
                    break;
                case 2:
                    adapter.notifyDataSetChanged();
                    closeLodindDialog();
                    Toast.makeText(SupAotoListActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    closeLodindDialog();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("生成补货单成功!")
                            .setPositive("确定", null)
                            .setWidth(0.5f)
                            .show(getSupportFragmentManager());

                    break;
                case 4:
                    closeLodindDialog();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("生成补货单失败："+msg.obj)
                            .setPositive("确定", null)
                            .setWidth(0.5f)
                            .show(getSupportFragmentManager());
                    break;
            }

        }
    };


    //下载门店
    private void downStore() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());

                    md_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });



    }


    private String inMark;
    private String outMark;
    private void showmd(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : md_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                yyyPopupWindow.dismiss();
                getDetail(md_Beens.get(position).getId());
                inMark = md_Beens.get(position).getId();
                tv_md.setText(md_Beens.get(position).getName());
            }
        });
    }
    private void showpsmd(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : md_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                yyyPopupWindow.dismiss();
                outMark = md_Beens.get(position).getId();
                tv_psmd.setText(md_Beens.get(position).getName());
            }
        });
    }



    @OnClick({R.id.tv_md, R.id.tv_bt_start,R.id.tv_psmd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_md:
                showmd(tv_md);
                break;
            case R.id.tv_bt_start:
                if (tv_md.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请选择门店", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tv_psmd.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请选择配送门店", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (beens.size() == 0) {
                    Toast.makeText(this, "没有商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                startSc();
                break;
            case R.id.tv_psmd:
                showpsmd(tv_psmd);
                break;
        }
    }


    private void startSc() {
        showLodingDialog("请求中...");
        beens.clear();
        Map<String,String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.replenishment");
        params.put("type", "201");
        params.put("table", "xb_base_safestorck");
        params.put("fun", "create");
        params.put("outmarket", outMark);
        params.put("inmarket", inMark);

        JSONArray array = new JSONArray();

        for (BhGoodsBeen been : beens) {
            JSONObject object = new JSONObject();
            try {
                object.put("marketid", inMark);
                object.put("goodsid", been.getGoodsid());
                object.put("sl", been.getSuj());
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        params.put("pds", array.toString());
        Log.i("login",params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    Log.i("login", jsonObject.getString("errMsg"));
                    String code = jsonObject.getString("errCode");
                    if (code.equals("100")) {
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 4;
                        message.obj = jsonObject.getString("errMsg");
                        handler.sendMessage(message);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 4;
                    message.obj = "解析异常";
                    handler.sendMessage(message);
                }

            }
        });
    }

    private void getDetail(String id){
        showLodingDialog("请求中...");
        beens.clear();
        Map<String,String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.replenishment");
        params.put("type", "201");
        params.put("table", "xb_base_safestorck");
        params.put("fun", "sujGoodsStock");

        JSONObject object = new JSONObject();
        try {
            object.put("marketid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    String code = jsonObject.getString("errCode");
                    if (code.equals("100")) {
                        List<BhGoodsBeen> list = new Gson().fromJson(result.toString(),
                                new TypeToken<List<BhGoodsBeen>>() {
                                }.getType());
                        beens.addAll(list);
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 2;
                        message.obj = jsonObject.getString("errMsg");
                        handler.sendMessage(message);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 2;
                    message.obj = "解析异常";
                    handler.sendMessage(message);
                }

            }
        });
    }


}
